<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Edit, Message, Lock, Setting } from '@element-plus/icons-vue'
import { getUserProfile, updateUserProfile, uploadAvatar, type UserProfileVO, type UserProfileUpdateDTO, type AvatarUploadDTO } from '@/apis/user/userAPI'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import MessageCenter from '@/views/userViews/message/index.vue'

// 加载状态
const loading = ref(false)

// 用户信息
const userInfo = ref({
  id:'',
  name: '',
  nickname: '',
  avatar: '@/assets/user-avatar.svg',
  gender: '',
  age: 0,
  phone: '',
  email: '',
  address: '',
  emergencyContact: '',
  bloodType: '',
  allergies: '',
  chronicDiseases: '',
  registrationDate: '',
  height: 0,
  weight: 0
})

// 用户Store
const userStore = useUserStore()

// 获取用户信息
const fetchUserProfile = async () => {
  loading.value = true
  try {
    const res = await getUserProfile()
    if (res.data) {
      // 将API返回的数据映射到组件中的用户信息
      const profile = res.data

      // 处理性别字段，将"1"转换为"男"，"2"转换为"女"
      let genderText = ''
      if (profile.sex === '1') {
        genderText = '男'
      } else if (profile.sex === '2') {
        genderText = '女'
      }

      // 处理头像字段，去除多余的空格和引号
      let avatarUrl = profile.avatar
      if (avatarUrl) {
        avatarUrl = avatarUrl.trim().replace(/[`'"]/g, '')
      }

      userInfo.value = {
        id: userStore.userId,
        name: profile.name || '',
        nickname: profile.nickname || '',
        avatar: avatarUrl || '@/assets/user-avatar.svg',
        gender: genderText,
        age: calculateAge(profile.birthday),
        phone: profile.phone || '',
        email: profile.email || '',
        address: profile.baseInfo || '',
        emergencyContact: '',  // API中没有对应字段
        bloodType: '',  // API中没有对应字段
        allergies: '',  // API中没有对应字段
        chronicDiseases: '',  // API中没有对应字段
        registrationDate: '',  // API中没有对应字段
        height: profile.height || 0,
        weight: profile.weight || 0
      }

      // 将用户信息存储到store中
      userStore.setUserInfo({
        userId: userStore.userId,
        username: profile.name,
        nickname: profile.nickname,
        avatar: avatarUrl
      })
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 根据生日计算年龄
const calculateAge = (birthday?: Date) => {
  if (!birthday) return 0
  const birthDate = new Date(birthday)
  const today = new Date()
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  return age
}

// 当前激活的标签页
const activeTab = ref('basic')

// 是否显示编辑表单
const showEditForm = ref(false)

// 切换编辑表单显示状态
const toggleEditForm = () => {
  showEditForm.value = !showEditForm.value
}

// 保存用户信息
const saveUserInfo = async () => {
  loading.value = true
  try {
    // 构建要更新的用户信息对象
    const updateData: UserProfileUpdateDTO = {
      id: userInfo.value.id, // 用户ID，这里使用固定值，实际应该从用户信息中获取
      name: userInfo.value.name,
      nickname: userInfo.value.nickname,
      sex: userInfo.value.gender,
      phone: userInfo.value.phone,
      email: userInfo.value.email,
      baseInfo: userInfo.value.address,
      height: userInfo.value.height,
      weight: userInfo.value.weight
      // 注意：生日等其他字段需要根据实际情况添加
    }

    // 调用API更新用户信息
    const res = await updateUserProfile(updateData)
    if (res) {
      ElMessage.success('个人信息更新成功')
      showEditForm.value = false

      // 更新store中的用户信息
      userStore.setUserInfo({
        userId: userStore.userId,
        username: updateData.name,
        nickname: updateData.nickname,
        avatar: userInfo.value.avatar
      })

      // 重新获取用户信息以确保显示最新数据
      await fetchUserProfile()
    } else {
      ElMessage.error('更新失败，请稍后重试')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新用户信息失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理头像上传
const handleAvatarChange = async (file: any) => {
  if (!file) return

  try {
    loading.value = true
    // 直接使用FormData上传文件
    const avatarData: AvatarUploadDTO = {
      file: file.raw
    }

    const res = await uploadAvatar(avatarData)
    if (res && res.data) {
      ElMessage.success('头像上传成功')

      // 处理返回的头像URL，去除多余的空格和引号
      let avatarUrl = res.data
      if (avatarUrl) {
        avatarUrl = avatarUrl.trim().replace(/[`'"]/g, '')
      }

      // 更新本地头像显示
      userInfo.value.avatar = avatarUrl
      // 更新store中的头像
      userStore.setAvatar(avatarUrl)
    } else {
      ElMessage.error('头像上传失败，请稍后重试')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传头像失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 在组件挂载时获取用户信息
onMounted(() => {
  fetchUserProfile()
})
</script>

<template>
  <div class="profile-container">
    <el-loading v-model:full-screen="loading" background="rgba(255, 255, 255, 0.7)" />
    <el-row :gutter="20">
      <!-- 左侧用户信息卡片 -->
      <el-col :span="8">
        <el-card shadow="hover" class="user-card">
          <div class="user-header">
            <div class="avatar-container">
              <el-avatar :size="80" :src="userInfo.avatar">{{ userInfo.name.charAt(0) }}</el-avatar>
              <div class="avatar-upload">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleAvatarChange">
                  <el-button type="primary" size="small" circle>
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </el-upload>
              </div>
            </div>
            <h2 class="user-name">{{ userInfo.name }}</h2>
            <p class="user-id">用户ID: {{ userInfo.id }}</p>
            <el-button type="primary" size="small" @click="toggleEditForm">
              <el-icon><Edit /></el-icon>
              编辑资料
            </el-button>
          </div>

          <el-divider />

          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-value">12</div>
              <div class="stat-label">预约次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">5</div>
              <div class="stat-label">就诊记录</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">8</div>
              <div class="stat-label">健康报告</div>
            </div>
          </div>

          <el-divider />

          <div class="contact-info">
            <div class="info-item">
              <el-icon><Message /></el-icon>
              <span>{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
              <el-icon><Lock /></el-icon>
              <span>上次登录: 今天 10:30</span>
            </div>
            <div class="info-item">
              <el-icon><Setting /></el-icon>
              <span>注册时间: {{ userInfo.registrationDate }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧内容区域 -->
      <el-col :span="16">
        <!-- 编辑表单 -->
        <el-card v-if="showEditForm" shadow="hover" class="mb-4">
          <template #header>
            <div class="card-header">
              <span>编辑个人信息</span>
            </div>
          </template>

          <el-form label-position="right" label-width="100px">
            <el-form-item label="姓名">
              <el-input v-model="userInfo.name" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="userInfo.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
              <el-input-number v-model="userInfo.age" :min="1" :max="120" />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input v-model="userInfo.phone" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="userInfo.email" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="userInfo.address" />
            </el-form-item>
            <el-form-item label="紧急联系人">
              <el-input v-model="userInfo.emergencyContact" />
            </el-form-item>
            <el-form-item label="血型">
              <el-select v-model="userInfo.bloodType">
                <el-option label="A型" value="A型" />
                <el-option label="B型" value="B型" />
                <el-option label="AB型" value="AB型" />
                <el-option label="O型" value="O型" />
              </el-select>
            </el-form-item>
            <el-form-item label="过敏史">
              <el-input v-model="userInfo.allergies" type="textarea" />
            </el-form-item>
            <el-form-item label="慢性病史">
              <el-input v-model="userInfo.chronicDiseases" type="textarea" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveUserInfo">保存</el-button>
              <el-button @click="toggleEditForm">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 用户详细信息标签页 -->
        <el-card v-else shadow="hover" class="mb-4">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
            </div>
          </template>

          <el-tabs v-model="activeTab" class="demo-tabs">
            <el-tab-pane label="基本信息" name="basic">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ userInfo.gender }}</el-descriptions-item>
                <el-descriptions-item label="年龄">{{ userInfo.age }}</el-descriptions-item>
                <el-descriptions-item label="手机号码">{{ userInfo.phone }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
                <el-descriptions-item label="地址" :span="2">{{ userInfo.address }}</el-descriptions-item>
                <el-descriptions-item label="紧急联系人" :span="2">{{ userInfo.emergencyContact }}</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>

            <el-tab-pane label="健康信息" name="health">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="血型">{{ userInfo.bloodType }}</el-descriptions-item>
                <el-descriptions-item label="过敏史">{{ userInfo.allergies }}</el-descriptions-item>
                <el-descriptions-item label="慢性病史" :span="2">{{ userInfo.chronicDiseases }}</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>

            <el-tab-pane label="账户安全" name="security">
              <el-empty description="暂无安全设置" />
            </el-tab-pane>
          </el-tabs>
        </el-card>

        <!-- 消息中心区域 -->
        <el-card shadow="hover" class="message-container">
          <template #header>
            <div class="card-header">
              <span>消息中心</span>
            </div>
          </template>

          <MessageCenter />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.profile-container {
  padding: 20px;
}

.user-card {
  height: 100%;
}

.user-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.avatar-container {
  position: relative;
  margin-bottom: 10px;
}

.avatar-upload {
  position: absolute;
  right: -5px;
  bottom: 0;
  z-index: 10;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.user-name {
  margin: 10px 0 5px;
  font-size: 18px;
  font-weight: bold;
}

.user-id {
  margin: 0 0 15px;
  color: #909399;
  font-size: 14px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.contact-info {
  padding: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
}

.info-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-4 {
  margin-bottom: 20px;
}

.message-container {
  margin-top: 20px;
}
</style>
